import { sysLogin, sysProfile, sysUser } from '@/api/user.js'
import { getToken, setToken } from '@/utils/auth.js'
import asyncRoutes from '@/router/modules/index.js'
import router from '@/router'
import { constantRoutes } from '@/router/index.js'
import { resetRouter } from '@/router/index.js'

const state = {
  token: getToken() || '',
  profile: ''
}

const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setProfile(state, value) {
    state.profile = value
  },
  // 退出登录
  logout(state) {
    state.token = ''
    setToken('')
    state.profile = ''
    resetRouter()
  }
}

const actions = {
  // 登录
  async toLogin({ commit }, value) {
    const res = await sysLogin(value)
    commit('setToken', res.data)
  },
  // 获取用户信息
  async getProfile({ state, commit }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    commit('setProfile', { ...res.data, ...res2.data })
    const newRoutes = asyncRoutes.filter((item) => {
      return state.profile.roles.menus.includes(item.name)
    })
    newRoutes.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(newRoutes)
    commit('routes/setRoutesList', [...constantRoutes, ...newRoutes], {
      root: true
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
